package middleware

import (
	"github.com/gin-gonic/gin"
	"strings"
	"web_app/models"
	"web_app/pak/jwt"
	"web_app/tool"
)

//AuthorizationMiddleware  用户授权中间件
func AuthorizationMiddleware() func(*gin.Context) {
	return func(c *gin.Context) {
		authHeader := c.Request.Header.Get("Authorization")
		if authHeader == "" {
			tool.Error(c, "登陆失效，token参数为空")
			c.Abort()
			return
		}

		// 按空格分割
		parts := strings.SplitN(authHeader, " ", 2)
		if !(len(parts) == 2 && parts[0] == "Bearer") {
			tool.Error(c, "auth格式有误")
			c.Abort()
			return
		}

		claims, err := jwt.ParseToken(parts[1])
		if err != nil {
			tool.Error(c, "无效的Token1")
			c.Abort()
			return
		}

		user, err := models.User{}.GetUserInfoByUserId(claims.UserId)
		if err != nil {
			tool.Error(c, err.Error())
			c.Abort()
			return
		}

		c.Set("userId", claims.UserId)
		c.Set("userName", claims.UserName)
		c.Set("avatar", user.Avatar)
		c.Next()
	}
}
